//
//  HRFollowDynamicPhotoView.m
//  Hear
//
//  Created by mac on 2017/5/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFollowDynamicPhotoView.h"
#import "YYKit.h"
#import "YYControl.h"
#import "YYPhotoGroupView.h"
static CGFloat const oneImageHeight = 120;
static CGFloat const smallHeight = 120;
static CGFloat const pading = 5;

@interface HRFollowDynamicPhotoView ()
@property (nonatomic, strong) NSArray<UIView *> *picViews;      // 图片

@end
@implementation HRFollowDynamicPhotoView

-(void)setPicArr:(NSArray *)picArr{
    _picArr = picArr;
    
    [self setImageView];
}

- (void)setImageView{
    NSArray *pics = _picArr;
    
    int picsCount = (int)pics.count;
    CGFloat leftPading = 15;

    for (int i = 0; i < 6; i ++) {
        UIView *imageView = _picViews[i];
        if (i >= picsCount) {
            [imageView.layer cancelCurrentImageRequest];
            imageView.hidden = YES;
        } else{
            imageView.hidden = NO;
            
            if (_picArr.count < 3){
                imageView.frame = CGRectMake(leftPading+i*((self.width-leftPading*2-pading)/2+pading), 0, (self.width-leftPading*2-pading)/2, oneImageHeight);
                
            }else{
                CGFloat smallWidth = (self.width-pading*2-leftPading*2)/3;
                imageView.frame = CGRectMake(leftPading + i %3*(smallWidth+pading), i/3*(smallHeight+pading), smallWidth, smallHeight);
            }
            [imageView.layer removeAnimationForKey:@"contents"];
            
            //[imageView.layer setImageURL:[NSURL URLWithString:_layout.dynamicModel.pics[i]]];
            //            [imageView.layer setImageURL:[NSURL URLWithString:_picArr[i]]];

//[NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=image/resize,h_%d,w_%d",_picArr[i],(int)imageView.height,(int)imageView.width]]
            
            @weakify(imageView);
            [imageView.layer setImageWithURL:_picArr[i]
                                 placeholder:[UIImage imageNamed:@"默认加载图"]
                                     options:YYWebImageOptionAvoidSetImage
                                  completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error){                             @strongify(imageView);
                                      if (!imageView) return;
                                      if (image && stage == YYWebImageStageFinished) {
                                          int width = image.size.width;
                                          int height = image.size.height;
                                          CGFloat scale = (height / width) / (imageView.height / imageView.width);
                                          if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                                              imageView.contentMode = UIViewContentModeScaleAspectFill;
                                              imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                          } else { // 高图只保留顶部
                                              imageView.contentMode = UIViewContentModeScaleAspectFill;
                                              imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                          }
                                          ((YYControl *)imageView).image = image;
                                          if (from != YYWebImageFromMemoryCacheFast) {
                                              CATransition *transition = [CATransition animation];
                                              transition.duration = 0.15;
                                              transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                              transition.type = kCATransitionFade;
                                              [imageView.layer addAnimation:transition forKey:@"contents"];
                                          }
                                      }
                                  }];
            
        }
    }
}





-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        WeakSelf
        self.picViews = [NSMutableArray array];
        NSMutableArray *picView = [NSMutableArray new];
        
        for (int i = 0; i < 6; i++) {
            YYControl *imageView = [YYControl new];
            imageView.userInteractionEnabled = YES;
            imageView.hidden = YES;
            imageView.clipsToBounds = YES;
            imageView.backgroundColor = CustomColor(244, 244, 244, 1);
            imageView.exclusiveTouch = YES;
//            imageView.touchBlock = ^(YYControl *view, YYGestureRecognizerState state, NSSet *touches, UIEvent *event) {
//                //                if (![weakSelf.cell.delegate respondsToSelector:@selector(cell:didClickImageAtIndex:)]) return;
//                if (state == YYGestureRecognizerStateEnded) {
//                    UITouch *touch = touches.anyObject;
//                    CGPoint p = [touch locationInView:view];
//                    if (CGRectContainsPoint(view.bounds, p)) {
//                        //[weak_self.cell.delegate cell:weak_self.cell didClickImageAtIndex:i];
//                        [weakSelf clickImageAtIndex:i];
//                    }
//                }
//            };
            
            UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [weakSelf clickImageAtIndex:i];
            }];
            [imageView addGestureRecognizer:imageTap];
            
            [picView addObject:imageView];
            
            
            [self addSubview:imageView];
        }
        
        _picViews = picView;
        
    }
    return self;
}
- (void)clickImageAtIndex:(NSUInteger)index{
    UIView *fromView = nil;
    NSMutableArray *items = [NSMutableArray new];
    NSArray *pics =_picArr;
    
    for (NSUInteger i = 0, max = pics.count; i < max; i++) {
        UIView *imgView = self.picViews[i];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.thumbView = imgView;
        item.largeImageURL = [NSURL URLWithString:pics[i]];
        item.largeImageSize = CGSizeMake(imgView.width, imgView.height);
        [items addObject:item];
        if (i == index) {
            fromView = imgView;
        }
    }
    
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:WINDOW animated:YES completion:nil];
}


+(CGSize)sizePhotoViewWithPhotoCount:(NSInteger)photoCount andToWidth:(CGFloat)width{
    CGSize photoSize = CGSizeZero;
    
    
    if (photoCount == 1){
        photoSize = CGSizeMake(width, oneImageHeight);
    }else if (photoCount == 2 ||photoCount == 3){
        
        photoSize = CGSizeMake(width, smallHeight);
        
    }else if  (photoCount > 3){
        photoSize = CGSizeMake(width, smallHeight*2+pading);
        
    }
    return photoSize;
}




@end
